const {
  getTemplateDropdownList,
  getInspectionTemplateById,
  creatInspection,
  getInspectionById,
  updateInspection
} = require('../../../api/inspection')
const { FormatDate } = require('../../../utils/FormDate')
const { clearEmptyKey } = require('../../../utils/clearEmptyKey')
const {
  getEventData,
  to,
  showToast,
  openLoading,
  closeLoading,
  backParentLoad
} = getApp()

Page({
  data: {
    formData: {},
    templateModeFormData: {},
    templateOptions: [],
    templateDetail: {},
    formType: '',
  },

  onLoad() {
    this.setNavTitle()
    this.getTemplateOptions()
    this.getDetail()
  },

  getLoadInit() {
    openLoading()
    Promise.all([this.getTemplateOptions(), this.getDetail()])
    closeLoading()
  },

  setNavTitle() {
    const type = this.options.type
    let title;
    if (type === 'add') {
      title = '巡检单录入'
    } else if (type === 'edit') {
      title = '巡检单修改'
    } else if (type === 'review') {
      title = '巡检单查看'
    }

    this.setData({
      formType: type
    })
    
    wx.setNavigationBarTitle({
      title,
    })
  },

  async getTemplateOptions() {
    const [err, data] = await to(getTemplateDropdownList());

    if (!err) {
      this.setData({
        templateOptions: data
      })
      return Promise.resolve()
    }
    return Promise.reject(err)
  },

  async getInspectionTemplateListById() {
    const params = {
      id: this.data.formData.inspectionTemplateId
    }
    openLoading()
    const [err, data] = await to(getInspectionTemplateById(params))
    closeLoading()
    if (!err) {
      this.setData({
        templateDetail: data,
        templateModeFormData: data.model
      })
    }
  },

  async getDetail() {
    const id = this.options.id;

    if (!id && id !== 0) {
      return Promise.resolve()
    }

    openLoading()
    const [err, data] = await to(getInspectionById({ id }))
    closeLoading()

    if (!err) {
      this.setData({
        ['formData.inspectionId']: data.inspectionId,
        ['formData.inspectionTemplateId']: data.inspectionTemplateId,
        ['formData.inspectionTitle']: data.inspectionTitle,
        ['formData.inspectionTime']: new FormatDate(data.inspectionTime).format('yyyy-MM-dd hh:mm'),
        templateDetail: JSON.parse(data.inspectionTemplateSnapshot),
        templateModeFormData: JSON.parse(data.inspectionModel)
      })

      return Promise.resolve()
    }
    return Promise.reject(err)
  },

  onCustomFormTypeChange(event) {
    const {
      type
    } = getEventData(event)
    this.setData({
      [`formData.${type}`]: event.detail
    })

    if (type === 'inspectionTemplateId') {
      if (event.detail) {
        this.getInspectionTemplateListById()
      } else {
        this.setData({
          templateDetail: {},
          templateModeFormData: {}
        })
      }
    }
  },

  onTemplateFormTypeChange(event) {
    const {
      type
    } = getEventData(event)
    this.setData({
      [`templateModeFormData.${type}`]: event.detail
    })
  },

  isNotEmpty(value) {
    const result = value + ''
    if (result === 'undefined' || result === 'null') {
      return false;
    }

    if (result.length === 0) {
      return false
    }
    return true
  },

  checkValidate() {
    const { formData, templateModeFormData, templateDetail } = this.data;

    if (!this.isNotEmpty(formData.inspectionTemplateId)) {
      showToast('请选择巡检模板')
      return false
    }

    if (!this.isNotEmpty(formData.inspectionTime)) {
      showToast('请选择巡检时间')
      return false
    }

    const rules = templateDetail.formDataList.filter(item => {
      return item.rules && item.rules.required
    }).map(item => {
      return {
        message: item.rules.required.message,
        fieldId: item.fieldId
      }
    })

    for (const key in templateModeFormData) {
      if (!this.isNotEmpty(templateModeFormData[key])) {
        const rule = rules.find(item => item.fieldId === key)
        if (rule) {
          showToast(rule.message)
          return false
        }
      }
    }

    return true
  },

  async handleSubmit() {
    const result = this.checkValidate()

    if (!result) return;
    const title = this.data.templateOptions.find(item => item.code === this.data.formData.inspectionTemplateId).name
    const params = {  
      inspectionTitle: title,
      inspectionTemplateId: this.data.formData.inspectionTemplateId,
      inspectionTime: this.data.formData.inspectionTime,
      inspectionModel: JSON.stringify(this.data.templateModeFormData),
      inspectionId: this.data.formData.inspectionId
    }

    clearEmptyKey(params)

    let apiName = creatInspection

    if (params.inspectionId) {
      apiName = updateInspection
    }
    openLoading()
    const [err, data] = await to(apiName(params))
    closeLoading()

    if (!err) {
      showToast({
        message: '保存成功',
        type: 'success',
        mask: true,
        onClose: () => {
          setTimeout(() => {
            backParentLoad()
          }, 1000)
        }
      })
    }
  }
})